package com.hll.javaweb.servlet.file;

import org.apache.commons.io.IOUtils;

import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.FileInputStream;
import java.io.IOException;
import java.net.URLEncoder;

/**
 * @author hll
 * @create 2022-05-10 13:31
 */
@WebServlet("/download-file")
public class Download extends HttpServlet {
  @Override
  protected void doGet(HttpServletRequest request, HttpServletResponse response)
      throws ServletException, IOException {
    String filename = "艾斯.jpg";
    response.setContentType(this.getServletContext().getMimeType(filename)); // 文件类型
    // Content-Disposition响应头，表示收到的数据怎么处理
    // attachment表示附件，表示下载使用
    // filename= 表示指定下载的文件名
    response.setHeader(
        "Content-Disposition", "attachment;filename=" + URLEncoder.encode(filename, "utf-8"));
    FileInputStream fis =
        new FileInputStream(this.getServletContext().getRealPath("/upload/" + filename));
    ServletOutputStream stream = response.getOutputStream();
    IOUtils.copy(fis, stream); // 使用commons.io工具输出流
    fis.close();
  }
}
